package com.manager.system.service.impl;

import com.manager.common.dao.SuperDao;
import com.manager.common.token.TokenUtils;
import com.manager.common.utils.MD5;
import com.manager.common.utils.ObjectUtils;
import com.manager.common.vo.PageVO;
import com.manager.model.*;
import com.manager.system.service.UserService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UserServiceImpl extends SuperDao<Object> implements UserService {

    @Override
    @Transactional
    public PageVO getUserMap(System_User user){
        List<Object> params = new ArrayList<Object>();

        String sql = "select t  ";
        String sql2 = " from System_User t  where 1 = 1 ";
        if(StringUtils.isNotEmpty(user.getUserName())){
            sql2 += " and t.userName like ?1 ";
            params.add("%" + user.getUserName() + "%");
        }

        List<System_User> list = this.getList(sql + sql2, params.toArray(), user.getStart(), user.getLimit(), "");
        for(System_User sys:list){

            List<System_User_Organization> uso = sys.getListuo();
            List<System_User_Role> our = sys.getListur();
            List<System_User_Permission> up = sys.getListup();

            if(uso != null && uso.size() > 0){
                for(System_User_Organization system_User_Organization:uso){
                    sys.setString1((sys.getString1() == null ? "" : sys.getString1()) + system_User_Organization.getSys_orga().getName()+",");
                    sys.setString2((sys.getString2() == null ? "" : sys.getString2()) + system_User_Organization.getSys_orga().getId()+",");
                }
                sys.setString1(sys.getString1().substring(0, sys.getString1().lastIndexOf(",")));
                sys.setString2(sys.getString2().substring(0, sys.getString2().lastIndexOf(",")));
            }

            if(our != null && our.size() > 0){
                for(System_User_Role system_User_Role:our){
                    sys.setString3((sys.getString3() == null ? "" : sys.getString3()) + system_User_Role.getSys_role().getName()+",");
                    sys.setString4((sys.getString4() == null ? "" : sys.getString4()) + system_User_Role.getSys_role().getId()+",");
                }
                sys.setString3(sys.getString3().substring(0, sys.getString3().lastIndexOf(",")));
                sys.setString4(sys.getString4().substring(0, sys.getString4().lastIndexOf(",")));
            }

            if(up != null && up.size() > 0){
                for(System_User_Permission systemUserPermission:up){
                    sys.setString5((sys.getString5() == null ? "" : sys.getString5()) + systemUserPermission.getSys_perm().getId()+",");
                }
                sys.setString5(sys.getString5().substring(0, sys.getString5().lastIndexOf(",")));
            }

        }
        JSONArray jsonArray = ObjectUtils.getJSONArray(System_User.config, list);
        int sum = this.getListCount( "select count(t.id) " + sql2, params.toArray(), "");
        int count = (int) Math.ceil((Double.valueOf(sum)/Double.valueOf(user.getLimit())));

        return PageVO.create(user.getStart(),count,jsonArray);
    }


    @Override
    @Transactional
    public void addUser(System_User model) throws Exception {
        // TODO Auto-generated method stub;

        if(StringUtils.isEmpty(model.getUserName())){
            throw new Exception("用户名称不能为空!");
        }

        String sql = " from  System_User t where t.userName = ?1 ";
        System_User systemUser = (System_User) this.getListOne(sql,new Object[]{model.getUserName()},"");

        if(systemUser != null){
            throw new Exception("用户名称不能相同!");
        }

        model.setPassword(MD5.getMD5(model.getPassword().getBytes()));

        this.addT(model);

        String permossionIds = model.getString1();
        String orgIds = model.getString2();
        String rolesIds = model.getString3();

        if(StringUtils.isNotEmpty(permossionIds)){
            String[] ids = permossionIds.split(",");
            for(String id:ids){
                System_Permission system_Permission = (System_Permission) this.getT(new System_Permission(), id);
                if(system_Permission == null){
                    continue;
                }

                System_User_Permission system_User_Permission = new System_User_Permission();
                system_User_Permission.setSys_perm(system_Permission);
                system_User_Permission.setSys_user(model);

                this.addT(system_User_Permission);
            }
        }

        if(StringUtils.isNotEmpty(orgIds)){
            String[] ids = orgIds.split(",");
            for(String id:ids){
                System_Organization org = (System_Organization) this.getT(new System_Organization(), id);
                if(org == null){
                    continue;
                }

                System_User_Organization system_User_Organization = new System_User_Organization();
                system_User_Organization.setSys_orga(org);
                system_User_Organization.setSys_user(model);

                this.addT(system_User_Organization);
            }
        }


        if(StringUtils.isNotEmpty(rolesIds)){
            String[] ids = rolesIds.split(",");
            for(String id:ids){
                System_User_Role system_User_Role = new System_User_Role();
                System_Role system_Role = (System_Role) this.getT(new System_Role(), id);
                if(system_Role == null){
                    continue;
                }
                system_User_Role.setSys_role(system_Role);
                system_User_Role.setSys_user(model);

                this.addT(system_User_Role);
            }
        }
    }

    @Override
    @Transactional
    public void updateUser(System_User model) throws Exception {
        // TODO Auto-generated method stub

        if(StringUtils.isEmpty(model.getUserName())){
            throw new Exception("用户名称不能为空!");
        }

        String sql = " from  System_User t where t.userName = ?1  and t.id != ?2 ";
        System_User systemUser = (System_User) this.getListOne(sql,new Object[]{model.getUserName(),model.getId()},"");

        if(systemUser != null){
            throw new Exception("用户名称不能相同!");
        }

        System_User user = (System_User) this.getT(new System_User(), model.getId());



        BeanUtils.copyProperties(model, user, new String[]{"listOrga","listur","listup","listuo","listFile","id","password"});

        if(!model.getPassword().equals(user.getPassword())){
            user.setPassword(MD5.getMD5(model.getPassword().getBytes()));
        }

        this.batchDelete(user.getListuo());
        this.batchDelete(user.getListur());
        this.batchDelete(user.getListup());

        this.updateT(user);


        String permossionIds = model.getString1();
        String orgIds = model.getString2();
        String rolesIds = model.getString3();

        if(StringUtils.isNotEmpty(permossionIds)){
            String[] ids = permossionIds.split(",");
            for(String id:ids){
                System_Permission system_Permission = (System_Permission) this.getT(new System_Permission(), id);
                if(system_Permission == null){
                    continue;
                }

                System_User_Permission system_User_Permission = new System_User_Permission();
                system_User_Permission.setSys_perm(system_Permission);
                system_User_Permission.setSys_user(user);

                this.addT(system_User_Permission);
            }
        }

        if(StringUtils.isNotEmpty(orgIds)){
            String[] ids = orgIds.split(",");
            for(String id:ids){
                System_Organization org = (System_Organization) this.getT(new System_Organization(), id);
                if(org == null){
                    continue;
                }

                System_User_Organization system_User_Organization = new System_User_Organization();
                system_User_Organization.setSys_orga(org);
                system_User_Organization.setSys_user(user);

                this.addT(system_User_Organization);
            }
        }


        if(StringUtils.isNotEmpty(rolesIds)){
            String[] ids = rolesIds.split(",");
            for(String id:ids){
                System_User_Role system_User_Role = new System_User_Role();
                System_Role system_Role = (System_Role) this.getT(new System_Role(), id);
                if(system_Role == null){
                    continue;
                }
                system_User_Role.setSys_role(system_Role);
                system_User_Role.setSys_user(user);

                this.addT(system_User_Role);
            }
        }
    }

    @Override
    @Transactional
    public JSONArray getUserJSONArray() {
        // TODO Auto-generated method stub
        String sql = "from System_User t ";
        List<System_User> list = this.getList(sql, 0, 0, "");
        JSONArray arr = ObjectUtils.getJSONArray(System_User.config, list);
        JSONArray jsonArr = new JSONArray();
        for(int i = 0;i < arr.size();i++){
            JSONObject json = new JSONObject();
            json.put("id", arr.getJSONObject(i).get("id"));
            json.put("name", arr.getJSONObject(i).get("realName"));
            json.put("pId", "0");

            jsonArr.add(json);
        }

        return jsonArr;
    }

    @Override
    @Transactional
    public JSONArray getMenuTree(System_User model) {
        // TODO Auto-generated method stub
        String sql = "from System_Permission t ";
        List<System_Permission> list = this.getList(sql, 0, 0, " order by t.sort ");
        JSONArray jsonArray = ObjectUtils.getJSONArray(System_Permission.config, list);
      /*  sql = "from System_User_Permission t where t.sys_user.id = ?0 ";
        List<System_User_Permission> list2 = this.getList(sql, new Object[]{model.getId()}, 0, 0);
*/
       /* for(int i = 0;i < jsonArray.size();i++){
            JSONObject json = jsonArray.getJSONObject(i);
            *//*for(System_User_Permission user_Permission:list2){
                if(json.getString("id").equals(user_Permission.getSys_perm().getId())){
                    json.put("checked", true);
                }
            }*//*

        }*/

        return jsonArray;
    }

    @Override
    public void deleteUser(System_User model) {
        // TODO Auto-generated method stub
        System_User sUser = (System_User) this.getT(new System_User(), model.getId());
        this.delete(sUser);
    }

    @Override
    public void updateUserPwsd(System_User model) {
        // TODO Auto-generated method stub
        System_User systemUser = TokenUtils.getLoginUser();
        System_User user = (System_User) this.getT(new System_User(), systemUser.getId());
        user.setPassword(model.getPassword());
        this.updateT(user);
    }

    @Override
    public JSONArray getUserArray() {
        // TODO Auto-generated method stub

        String sql = "from System_User t where 1 = 1 ";
        List<System_User> list = this.getList(sql, 0, 0, "");

        if(list == null){
            return new JSONArray();
        }

        return ObjectUtils.getJSONArray(System_User.config, list);
    }

    @Override
    public System_User getUser(System_User model) {
        System_User user = (System_User) this.getT(new System_User(), model.getId());
        return user;
    }

    @Override
    public void addRemoteUser(System_User model, JSONArray orgCodes) {
        // TODO Auto-generated method stub
        this.addT(model);
        for(int i = 0;i < orgCodes.size();i++){
            String departCode = orgCodes.getJSONObject(i).getString("departCode");
            String sql = " from System_Organization t where t.name = ?0 ";
            System_Organization organization = (System_Organization) this.getListOne(sql, new Object[]{departCode}, "");
            if(organization == null){
                continue;
            }
            System_User_Organization system_User_Organization = new System_User_Organization();
            system_User_Organization.setSys_user(model);
            system_User_Organization.setSys_orga(organization);
            this.addT(system_User_Organization);
        }
    }

    @Override
    public void updateRemoteUser(System_User model, JSONArray orgCodes) {
        // TODO Auto-generated method stub

        System_User user = (System_User) this.getT(new System_User(), model.getId());

        BeanUtils.copyProperties(model, user, new String[]{"listOrga","listur","listup","listuo","listFile","id","password"});

        this.batchDelete(user.getListuo());
        this.batchDelete(user.getListur());
        this.batchDelete(user.getListup());

        this.updateT(user);

        for(int i = 0;i < orgCodes.size();i++){
            String departCode = orgCodes.getJSONObject(i).getString("departCode");
            String sql = " from System_Organization t where t.name = ?0 ";
            System_Organization organization = (System_Organization) this.getListOne(sql, new Object[]{departCode}, "");
            if(organization == null){
                continue;
            }
            System_User_Organization system_User_Organization = new System_User_Organization();
            system_User_Organization.setSys_user(user);
            system_User_Organization.setSys_orga(organization);
            this.addT(system_User_Organization);
        }

    }

    @Override
    public System_User getUser(String id) {
        // TODO Auto-generated method stub
        System_User user = (System_User) this.getT(new System_User(), id);
        return user;
    }

    @Override
    public List<System_User> getSystemUserList() {
        String sql = "  select t from System_User t where t.isOpen = 1 ";
        List<System_User> list = this.getList(sql,0,0,"");

        return list;
    }

    @Override
    public List<System_Permission> getSystemPermissionList(String name) {
        List<Object> params = new ArrayList<>();
        String sql = " from System_Permission t where 1 = 1 ";
        if(StringUtils.isNotEmpty(name)){
            sql += " and t.name like # ";
            params.add("%" + name + "%");
        }
        sql = ObjectUtils.replaceIndexByList(sql,params);
        List<System_Permission> list = this.getList(sql,params.toArray(), 0, 10, "");
        return list;
    }
}
